﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Threading;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for ProductionOrder.xaml
    /// </summary>
    public partial class JLTAV37 : DocumentBase
    {
        #region-------------Properties-----------------------
        Grid Lastjob;
        ITXEXRPT ITXEXRPT;
        public ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        INTEXDBC INTEXDBC
        {
            get
            {
                return app.INTEXDBC;
            }
        }

        public ITXSCHEDULER Scheduler = new ITXSCHEDULER();

        private readonly TaskScheduler _syncContextTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
        private NameScope pagescope = new System.Windows.NameScope();
        int year = 0, month = 0, day = 0;
        bool FilterByMachineType = false;
        JLTAV37Data m_Data;
        public SETINTEXDB SetEnv
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetEnv");
            }
        }
        public SETINTEXDB SetVKK
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetVKK");
            }
        }
        public SETINTEXDB SetVKP
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetVKP");
            }
        }
        public SETINTEXDB SetData
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetData");
            }
        }
        public SETINTEXDB SetProd
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetProd");
            }
        }
        #region=====vwAMSTAMM=======
        CollectionViewSource vwAMSTAMM
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwAMSTAMM");
            }
        }
        DataRow dwAMSTAMM
        {
            get
            {
                if (vwAMSTAMM.View == null)
                    return null;
                if ((DataRowView)vwAMSTAMM.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwAMSTAMM.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwBMKRF=======
        CollectionViewSource vwBMKRF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwBMKRF");
            }
        }
        DataRow dwBMKRF
        {
            get
            {
                if (vwBMKRF.View == null)
                    return null;
                if ((DataRowView)vwBMKRF.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwBMKRF.View.CurrentItem).Row;
            }
        }
        #endregion
        BindingListCollectionView cvMKRF
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgMABP.ItemsSource);
            }
        }
        BindingListCollectionView cvSMKRF
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgSABP.ItemsSource);
            }
        }
        string KRS
        {
            get
            {
                return m_Data.Right("  " + txtABPAUFKRS.Text.ToString().Trim(), 2);
            }
            set
            {
                txtABPAUFKRS.Text = value;
            }
        }
        string LFD
        {
            get
            {
                return m_Data.Right("000000" + txtABPAUFLFD.Text.ToString().Trim(), 6); ;
            }
            set
            {
                txtABPAUFLFD.Text = value;
            }
        }
        string POS
        {
            get
            {
                return m_Data.Right("000" + txtABPAUFPOS.Text.ToString().Trim(), 3); ;
            }
            set
            {
                txtABPAUFPOS.Text = value;
            }
        }
        string KSTKRS
        {
            get
            {
                return m_Data.Right("  " + this.txtKSTKRS.Text.ToString().Trim(), 2);
            }
            set
            {
                txtKSTKRS.Text = value;
            }
        }
        string KST
        {
            get
            {
                return m_Data.Right("000000" + this.txtFKST.Text.ToString().Trim(), 4); ;
            }
            set
            {
                txtFKST.Text = value;
            }
        }
        string AGANG
        {
            get
            {
                return m_Data.Left(this.txtAGANG.Text.ToString().PadRight(15), 15);
            }
            set
            {
                txtAGANG.Text = value;
            }
        }
        string machtyp
        {
            get
            {
                return m_Data.Left(this.txtMachTyp.Text.ToString().PadRight(8), 8);
            }
            set
            {
                txtMachTyp.Text = value;
            }
        }

        #endregion
        public JLTAV37()
        {
            InitializeComponent();
            this.Name = "智能排产";

        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            base.SetUp(dicParamater);
            InitializeComponent();
            NameScope.SetNameScope(this, pagescope);
            m_Data = new JLTAV37Data();
            ITXEXRPT = new ITXEXRPT();
            ITXEXRPT.Root = "C:\\IntexReport";
            ITXEXRPT.strCompany = app.company;
            ITXEXRPT.PrintType = "OpenExcel";
            txtABPAUFKRS.Text = "T2";
            txtABPAUFLFD.Text = "001336";
            txtABPAUFPOS.Text = "002";
            KSTKRS = "  ";
            KST = "0210";
            AGANG = "RS";
            machtyp = "RSGYG";
            m_Data.KSTKRS = KSTKRS;
            m_Data.KST = KST;
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            DataSet SResult;
            try
            {
                if (IsLoaded) return;
                IsLoaded = true;
                /*if (!SetData.Tables.Contains("BMKRF"))
                {
                    DataTable tb = SetData.ICC_MKRF.Clone();
                    tb.TableName = "BMKRF";
                    SetData.Merge(tb);
                }*/
                SResult = m_Data.LoadEnv();
                SetEnv.Clear();
                foreach (DataTable tb in SResult.Tables)
                {
                    SetEnv.Merge(tb);
                }
                SetupMachine();
                btnRefresh_Click(null, null);
                vwBMKRF.View.CurrentChanged += vwBMKRF_CurrentChanged;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;

        }
        public delegate DataSet AsyncRunHandle(object p1 = null, object p2 = null, object p3 = null, object p4 = null, object p5 = null);
        string _sTemp = string.Empty;

        public void AsyncRun(string TaskType, object p1 = null, object p2 = null, object p3 = null, object p4 = null, object p5 = null)
        {
            AsyncRunHandle fHandle = null;
            AsyncCallback callback = null;
            IAsyncResult aResult = null;
            WaitHandle waitHandle = null;
            switch (TaskType)
            {
                case "YarnDyeWeavingDB":
                    fHandle = new AsyncRunHandle(Scheduler.SpinningDB);
                    callback = new AsyncCallback(this.AsyncCallbackImpl);
                    aResult = fHandle.BeginInvoke(p1, p2, p3, p4, p5, callback, fHandle);
                    waitHandle = aResult.AsyncWaitHandle;
                    waitHandle.WaitOne();
                    break;
                case "StartSchedule":
                    fHandle = new AsyncRunHandle(Scheduler.StartSchedule);
                    callback = new AsyncCallback(this.AsyncCallbackImpl);
                    aResult = fHandle.BeginInvoke(p1, p2, p3, p4, p5, callback, fHandle);
                    waitHandle = aResult.AsyncWaitHandle;
                    waitHandle.WaitOne();
                    break;
            }
        }
        public void AsyncCallbackImpl(IAsyncResult run)
        {
            AsyncRunHandle handle = run.AsyncState as AsyncRunHandle;
            DataSet SResult = handle.EndInvoke(run);
            switch (handle.Method.Name)
            {
                case "YarnDyeWeavingDB":
                    Task.Factory.StartNew(() => btnQuery_Click(null, null), new CancellationTokenSource().Token, TaskCreationOptions.None, _syncContextTaskScheduler).Wait();
                    break;
                case "StartSchedule":
                    Scheduler.SaveTempSchedule(SResult);
                    Task.Factory.StartNew(() => btnQuery_Click(null, null), new CancellationTokenSource().Token, TaskCreationOptions.None, _syncContextTaskScheduler).Wait();
                    break;
            }
        }
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            //异步执行更新数据库，
            //完成后，异步执行查询
            AsyncRun("YarnDyeWeavingDB", KSTKRS, KST, AGANG);
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                DataSet Result = new DataSet();
                DataRow dwData = SetData.ICC_MKRF.NewRow();
                dwData["ABFMANDANT"] = "00";
                dwData["ABFKSTKRS"] = KSTKRS;
                dwData["ABFKST"] = KST;
                using (new LongOperation(this, "正在生成报表，请耐心等待"))
                {
                    Result = m_Data.BuildData(dwData);
                }
                SetData.Clear();
                SetData.Merge(Result);
                SetEnv.ICC_MKRF.Clear();
                if (SetData.Tables.Contains("BMKRF"))
                {
                    SetEnv.ICC_MKRF.Merge(SetData.Tables["BMKRF"]);
                }
                JobControls = Scheduler.ShowMachine(SetData, SetEnv, MachineControls, pagescope, _syncContextTaskScheduler, GDensity);
                if (vwBMKRF != null)
                {
                    if (vwBMKRF.View != null)
                    {
                        vwBMKRF.View.MoveCurrentToFirst();
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }


        private void AM_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (dwAMSTAMM == null)
                return;
            Grid machine = (Grid)this.FindName("mx" + Helpers.Helper.GetMachineID(dwAMSTAMM["AMNRKRS"].ToString(), dwAMSTAMM["AMLFDNR"].ToString(), dwAMSTAMM["AMPOS"].ToString()));
            if (machine != null)
            {
                FocusJob(mainViewer, machines, machine);
            }
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string jobid = KRS + "_" + LFD + "_" + POS;

                Grid job = (Grid)this.FindName("m1" + jobid);
                if (job == null)
                {
                    job = (Grid)this.FindName("s1" + jobid);
                }
                if (job != null)
                {
                    FocusJob(mainViewer, machines, job);

                }
                DataRow dwJob = null;
                string filter = "ABFAUFKRS='" + KRS + "' AND ABFAUFLFD='" + LFD + "' AND ABFAUFPOS='" + POS + "'";
                DataRow[] rows = SetData.ICC_MKRF.Select(filter);
                foreach (DataRow row in rows)
                {
                    dwJob = row;
                }
                if (dwJob == null)
                    return;
                DataTable tb;

                filter = "VKPAUFKRS='" + dwJob["VKPAUFKRS"].ToString() + "' AND VKPAUFLFD='" + dwJob["VKPAUFLFD"].ToString() + "'";
                rows = SetData.ICC_MKRF.Select(filter);
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "VKKMKRF";
                    if (SetVKK.Tables.Contains("VKKMKRF"))
                    {
                        SetVKK.Tables["VKKMKRF"].Clear();
                    }
                    SetVKK.Merge(tb);
                }
                filter = "VKPAUFKRS='" + dwJob["VKPAUFKRS"].ToString() + "' AND VKPAUFLFD='" + dwJob["VKPAUFLFD"].ToString() + "' AND VKPAUFPOS='" + dwJob["VKPAUFPOS"].ToString() + "'";
                rows = SetData.ICC_MKRF.Select(filter);
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "VKPMKRF";
                    if (SetVKP.Tables.Contains("VKPMKRF"))
                    {
                        SetVKP.Tables["VKPMKRF"].Clear();
                    }
                    SetVKP.Merge(tb);
                }
                filter = "ABPART='" + dwJob["ABPART"].ToString() + "' AND ABPVAR='" + dwJob["ABPVAR"].ToString() + "' AND ABPFARBE='" + dwJob["ABPFARBE"].ToString() + "'";
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "FMKRF";
                    if (SetProd.Tables.Contains("FMKRF"))
                    {
                        SetProd.Tables["FMKRF"].Clear();
                    }
                    SetProd.Merge(tb);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void tabMS_GotFocus(object sender, RoutedEventArgs e)
        {
            FilterByMachineType = true;
        }
        private void tabMS_LostFocus(object sender, RoutedEventArgs e)
        {

        }
        private void btnSplit_Click(object sender, RoutedEventArgs e)
        {
            if (dwBMKRF == null)
            {
                MessageBox.Show("请选择一个任务");
                return;
            }
            if (dwBMKRF["MKFTP"].ToString() != "0000")
            {
                MessageBox.Show("必需从原始记录上拆分");
                return;
            }
            int NNUM = Convert.ToInt16(dwBMKRF["JP50"].ToString());
            dwBMKRF["JP50"] = NNUM++;
            //获得最大号，如果已经拆分过，增加一个标志 JP50=次数
            DataRow dwNMRKF = SetEnv.ICC_MKRF.Rows.Add();
            dwNMRKF.ItemArray = dwBMKRF.ItemArray;
            dwNMRKF["ABAID"] = INTEXDBC.GetSeq();
            dwNMRKF["MKFTP"] = Helpers.Helper.Right("0000" + dwBMKRF["JP50"].ToString(), 4);

            double qtybase = 1;
            int MKFSME = Convert.ToInt16(dwBMKRF["MKFSME"].ToString());
            qtybase = Convert.ToDouble(dwBMKRF["MKFSMG" + MKFSME].ToString());
            if (txtSplitQty.Text.ToString().Trim() == "")
                txtSplitQty.Text = "0";
            double qty = Convert.ToDouble(txtSplitQty.Text.ToString());
            double ratio = qty / qtybase;
            for (int i = 1; i < 9; i++)
            {
                dwBMKRF["MKFSMG" + i] = Math.Round(qty * (1 - ratio));
                dwNMRKF["MKFSMG" + i] = Math.Round(qty * (1 - ratio));
            }
            INTEXDBC.SaveICC_MKRF(dwNMRKF);
            INTEXDBC.SaveICC_MKRF(dwBMKRF);
            var qA = from DataRow row in SetData.ICC_MKRF.AsEnumerable()
                     where row["ABAID"].ToString() == dwBMKRF["ABAID"].ToString()
                     && row["ABFAUFKRS"].ToString() == dwBMKRF["ABFAUFKRS"].ToString()
                     && row["ABFAUFLFD"].ToString() == dwBMKRF["ABFAUFLFD"].ToString()
                     && row["ABFAUFPOS"].ToString() == dwBMKRF["ABFAUFPOS"].ToString()
                     && row["MKFTP"].ToString() == dwBMKRF["MKFTP"].ToString()
                     select row;
            foreach (DataRow row in qA)
            {
                row["MKFTP"] = dwBMKRF["MKFTP"];
                DataRow rowN = SetData.ICC_MKRF.Rows.Add();
                rowN["ABAID"] = dwNMRKF["ABAID"];
                rowN["MKFTP"] = dwNMRKF["MKFTP"];
                for (int i = 1; i < 9; i++)
                {
                    row["MKFSMG" + i] = dwBMKRF["MKFSMG" + i];
                    rowN["MKFSMG" + i] = dwNMRKF["MKFSMG" + i];
                }
            }
            //保存拆分结果
        }
        private void TabItem_GotFocus(object sender, RoutedEventArgs e)
        {
            FilterByMachineType = false;
        }
        private void btnConfirmSchedule_Click(object sender, RoutedEventArgs e)
        {
            if (dwBMKRF == null)
                return;
            Scheduler.SaveSchedule(dwBMKRF, true);
        }
        private void btnFilter_Click(object sender, RoutedEventArgs e)
        {
            string filter = "ABFSTATUS=' ' AND ABFISTARTDAT=0  AND SPCONFIRM='        ' ";
            cvMKRF.CustomFilter = filter;
        }
        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            cvMKRF.CustomFilter = null;
        }
        private void btnSClear_Click(object sender, RoutedEventArgs e)
        {
            cvSMKRF.CustomFilter = null;
        }
        private void btnSFilter_Click(object sender, RoutedEventArgs e)
        {
            if (txtDate.Text.ToString().Trim() == "")
            {
                MessageBox.Show("请输入截止日期!");
                return;
            }
            string filter = "MKFPLDATV<=" + txtDate.Text.ToString() + "";
            cvMKRF.CustomFilter = filter;
            DataRow[] rows = SetData.ICC_MKRF.Select(filter);
            if (rows.Length > 0)
            {
                DataTable tb = rows.CopyToDataTable();
                SetEnv.ICC_MKRF.Clear();
                SetEnv.ICC_MKRF.Merge(tb);
            }
        }
        private void btnPrint_Click(object sender, EventArgs e)
        {
            ITXEXRPT.dsSource = SetEnv; ;
            ITXEXRPT.DocType = "JLTAVDOC";
            ITXEXRPT.strExcelFile = @"JLT\JLTAV37.xls";
        }
    }
}
